package com.nxp.nfc_demo.activities;

import java.util.Locale;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.nfc.NfcAdapter;
import android.nfc.NfcAdapter.ReaderCallback;
import android.nfc.Tag;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nxp.NFC2COM.R;
import com.nxp.nfc_demo.reader.Ntag_Get_Version.Prod;
import com.nxp.nfc_demo.reader.Ntag_I2C_Demo;

@SuppressLint("NewApi")
public class ReadMemoryActivity extends Activity {
	private PendingIntent pendingIntent;
	private NfcAdapter mAdapter;
	public static Context mContext;

	public Ntag_I2C_Demo demo;

	public static LinearLayout ll;

	ProgressDialog dialog;

	
	private ReaderCallback createReaderCallback(final Activity main) {
		return new ReaderCallback() {

			@Override
			public void onTagDiscovered(final Tag tag) {

				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						startDemo(tag);
					}
				});
			}

		};
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_readmemory);

		// Get the context reference
		mContext = getApplicationContext();
		ll = (LinearLayout) findViewById(R.id.layoutPages);

		// Add Foreground dispatcher
		mAdapter = NfcAdapter.getDefaultAdapter(this);
		pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
				getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
	}

	@SuppressLint("NewApi")
	@Override
	public void onPause() {
		super.onPause();
		if (mAdapter != null)
		{
			if (Build.VERSION.SDK_INT >= 19)
				mAdapter.disableReaderMode(this);
			else
				mAdapter.disableForegroundDispatch(this);
		}
	}

	@TargetApi(Build.VERSION_CODES.KITKAT)
	@Override
	public void onResume() {
		super.onResume();
		
		if (mAdapter != null) {
			Bundle options = new Bundle();
		    options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 20);

			if (Build.VERSION.SDK_INT >= 19) {
				mAdapter.enableReaderMode(this, createReaderCallback(this),
						NfcAdapter.FLAG_READER_NFC_A,
								Bundle.EMPTY);
			} else {
				mAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
			}
		}
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle presses on the action bar items
		if (item.getItemId() == R.id.action_about) {
			showAboutDialog();

			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	protected void onNewIntent(Intent nfc_intent) {
		Tag tag = nfc_intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);		
		startDemo(tag);
	}

	private void startDemo(Tag tag) {
		// Clean the GUI
		((ImageView) findViewById(R.id.imageTap)).setVisibility(View.GONE);
		((TextView) findViewById(R.id.textTap)).setVisibility(View.GONE);

		((LinearLayout) findViewById(R.id.layoutPages))
				.setVisibility(View.VISIBLE);

		ll.removeAllViews();

		// Complete the task in a new thread in order to be able to show the
		// dialog
		demo = new Ntag_I2C_Demo(tag, this);
		if(!demo.isReady())
			return;

		// Launch the thread
		new readTask().execute();
	}

	public void setContent(byte[] b) {
		// Check if the data has successfully been read
		if (b == null) {
			Toast.makeText(mContext, "Error reading the memory content",
					Toast.LENGTH_LONG).show();
		} else {
			
			for (int i = 0, j = 0; i < b.length; i = i + 4, j++) {
				String sPage = "";
				
				// Page Number
				sPage = sPage
						.concat("["
								+ "000".substring(Integer.toHexString(j)
										.length())
								+ Integer.toHexString(j).toUpperCase(
										Locale.getDefault()) + "]  ");

				// Hexadecimal values
				sPage = sPage.concat("00".substring(Integer.toHexString(
						b[i] & 0xFF).length())
						+ Integer.toHexString(b[i] & 0xFF).toUpperCase(
								Locale.getDefault())
						+ ":"
						+ "00".substring(Integer.toHexString(b[i + 1] & 0xFF)
								.length())
						+ Integer.toHexString(b[i + 1] & 0xFF).toUpperCase(
								Locale.getDefault())
						+ ":"
						+ "00".substring(Integer.toHexString(b[i + 2] & 0xFF)
								.length())
						+ Integer.toHexString(b[i + 2] & 0xFF).toUpperCase(
								Locale.getDefault())
						+ ":"
						+ "00".substring(Integer.toHexString(b[i + 3] & 0xFF)
								.length())
						+ Integer.toHexString(b[i + 3] & 0xFF).toUpperCase(
								Locale.getDefault()) + " ");

				// ASCII values
				if (j > 3) {
					byte[] tempAsc = new byte[4];

					// Only printable characters are displayed
					for (int k = 0; k < 4; k++) {
						if (b[i + k] < 0x20 || b[i + k] > 0x7D)
							tempAsc[k] = '.';
						else
							tempAsc[k] = b[i + k];
					}

					sPage = sPage.concat("|" + new String(tempAsc) + "|");
				}

				TextView tPage = new TextView(mContext);
				tPage.setLayoutParams(new LinearLayout.LayoutParams(
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
				tPage.setText(sPage);
				tPage.setTextColor(Color.BLACK);
				tPage.setTextSize(14);
				tPage.setTypeface(Typeface.MONOSPACE);

				ll.addView(tPage);
			}
		}
	}

	private class readTask extends AsyncTask<Intent, Integer, byte[]> {
		@Override
		protected void onPostExecute(byte[] bytes) {
			// Action completed
			dialog.dismiss();

			setContent(bytes);
		}

		@Override
		protected byte[] doInBackground(Intent... nfc_intent) {
			// Read content and print it on the screen
			byte[] response = demo.readTagContent();

			// Get the tag
			return response;
		}

		@Override
		protected void onPreExecute() {
			// Show the progress dialog on the screen to inform about the action
			dialog = ProgressDialog.show(ReadMemoryActivity.this, "Reading",
					"Reading memory content ...", true, true);
		}
	}

	protected void showAboutDialog() {
		Intent intent = null;
		intent= new Intent(this, VersionInfoActivity.class);		
		startActivity(intent);
	}
}
